<?php

class SiteController extends Controller {

    public $layout = 'main';

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'error', 'login', 'logout'),
                'users' => array('*'),
            )
        );
    }

    public function filters() {
        return [ 'accessControl'];
    }

    public function actionIndex() {
    	if( !Yii::app()->user->isGuest ) $this->redirect( '/news' );
        $this->render('index');
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionLogin( $username, $password ) {
        $user = new UserIdentity($username, $password);
        $user->authenticate();

        switch ($user->errorCode) {
            case $user::ERROR_USERNAME_INVALID:
                $this->renderJSON([ 'error' => Yii::t('site', "Username doesn't exists")]);
                break;
            case $user::ERROR_PASSWORD_INVALID:
                $this->renderJSON([ 'error' => Yii::t('site', 'Incorrect password')]);
                break;
            case $user::ERROR_NONE:
                Yii::app()->user->login( $user, Yii::app()->params['rememberMeTime'] );
                $this->renderJSON([ 'result' => 'OK']);
                break;
        }
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}
